package org.jeecg.modules.device.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhouwr.common.device.vo.report.ReportDataVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.device.entity.DataReport;
import org.jeecg.modules.device.mapper.DataReportMapper;
import org.jeecg.modules.device.service.IDataReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Description: 设备上传数据
 * @Author: jeecg-boot
 * @Date: 2020-05-14
 * @Version: V1.0
 */
@Api(tags = "设备上传数据")
@RestController
@RequestMapping("/message/data")
@Slf4j
public class DataReportController extends JeecgController<DataReport, IDataReportService> {
    @Autowired
    private IDataReportService dataService;
    @Autowired
    private DataReportMapper reportMapper;


    /**
     * 分页列表查询
     *
     * @param instanceId
     * @param beginDate
     * @param endDate
     * @param pageNo
     * @param pageSize
     * @return
     */
    @AutoLog(value = "设备上传数据-分页列表查询")
    @ApiOperation(value = "设备上传数据-分页列表查询", notes = "设备上传数据-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(
            @RequestParam(name = "instanceId", required = false) String instanceId,
            @RequestParam(name = "createTime_begin", required = false) String beginDate,
            @RequestParam(name = "createTime_end", required = false) String endDate,
            @RequestParam(name = "pageNo") Integer pageNo,
            @RequestParam(name = "pageSize") Integer pageSize
    ) {
        try {
            Date startDate = DateUtils.parseDate(beginDate, "yyyy-MM-dd HH:mm:ss");
            Date endDate1 = DateUtils.parseDate(endDate, "yyyy-MM-dd hh:mm:ss");
            List<ReportDataVo> reportDataVos = reportMapper.selectReportData(instanceId, startDate, endDate1, (pageNo - 1) * pageSize, pageSize);
            reportDataVos.forEach(reportDataVo -> {
                log.info("{}", JSON.toJSON(reportDataVo));
            });
            IPage<ReportDataVo> pageList = new Page<ReportDataVo>(pageNo, pageSize);
            pageList.setRecords(reportDataVos);
            Long total = reportMapper.selectReportDataTotal(instanceId, startDate, endDate1, (pageNo - 1) * pageSize, pageSize);
            pageList.setTotal(total);
            return Result.ok(pageList);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        LambdaQueryWrapper<DataReport> queryWrapper = new LambdaQueryWrapper<DataReport>();
        try {
            queryWrapper.eq(StringUtils.isNotBlank(instanceId), DataReport::getInstanceId, instanceId);
            if (StringUtils.isNotBlank(beginDate)) {
                queryWrapper.ge(DataReport::getCreateTime, DateUtils.parseDate(beginDate, "yyyy-MM-dd hh:mm:ss"));
            }
            if (StringUtils.isNotBlank(endDate)) {
                queryWrapper.le(DataReport::getCreateTime, DateUtils.parseDate(endDate, "yyyy-MM-dd hh:mm:ss"));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        queryWrapper.orderByDesc(DataReport::getCreateTime);

        Page<DataReport> page = new Page<DataReport>(pageNo, pageSize);
        IPage<DataReport> pageList = dataService.page(page, queryWrapper);
        this.dataService.reportExtents(pageList);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param data
     * @return
     */
    @AutoLog(value = "设备上传数据-添加")
    @ApiOperation(value = "设备上传数据-添加", notes = "设备上传数据-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody DataReport data) {
        dataService.save(data);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param data
     * @return
     */
    @AutoLog(value = "设备上传数据-编辑")
    @ApiOperation(value = "设备上传数据-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody DataReport data) {
        dataService.updateById(data);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "设备上传数据-通过id删除")
    @ApiOperation(value = "设备上传数据-通过id删除", notes = "设备上传数据-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        dataService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "设备上传数据-批量删除")
    @ApiOperation(value = "设备上传数据-批量删除", notes = "设备上传数据-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.dataService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "设备上传数据-通过id查询")
    @ApiOperation(value = "设备上传数据-通过id查询", notes = "设备上传数据-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        DataReport data = dataService.getById(id);
        if (data == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(data);
    }

    /**
     * 获取总数据计数
     *
     * @param instanceId
     * @return
     */
    @GetMapping(value = "/getTotalDataCount")
    public JSONObject getTotalDataCount(@RequestParam(name = "instanceId", required = false) String instanceId) {
        JSONObject json = new JSONObject();
        json.put("totalDataCount", dataService.lambdaQuery().eq(StringUtils.isNotBlank(instanceId), DataReport::getInstanceId, instanceId).count());
        return json;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param data
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, DataReport data) {
        return super.exportXls(request, data, DataReport.class, "设备上传数据");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, DataReport.class);
    }

}
